import React, { useState, useEffect } from 'react';
import { Input, Tag, Spin, Modal, Divider, Empty } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { doFetch, getFetch } from '@/utils/doFetch';
import AddTag from './addtag';

function CUTags({ company_id }) {
  const tagPlusStyle = {
    borderStyle: 'dashed',
    cursor: 'pointer',
  };
  const [modal, setModal] = useState({
    open: false,
    onCancel: () => {
      setModal((s) => ({
        ...s,
        open: false,
      }));
    },
  });

  //查询name
  const [name, setName] = useState(null);

  //存储当前即将提交的ids
  const [saveTagids, setSaveTagids] = useState([]);

  const { data, refresh } = useRequest(
    async () => {
      let res = await getFetch({ url: '/wbn-api/company_tag', params: { company_id } });
      return res?.data?.dataList;
    },
    {
      debounceWait: 400,
      onSuccess: (res) => {
        const ids = res?.map((it) => it?.tag_id);
        setSaveTagids(ids);
      },
    },
  );

  const { run, loading } = useRequest(doFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      refresh?.();
    },
  });

  const myalltags = useRequest(
    async () => {
      if (!modal?.open) {
        return;
      }
      let res = await getFetch({ url: '/wbn-api/tag', params: { is_self: 1, name: name } });
      return res?.data?.dataList;
    },
    {
      debounceWait: 400,
      refreshDeps: [name, modal?.open],
    },
  );

  const handleClose = (val,is_refresh) => {
    setSaveTagids((s) => {
      let news = JSON.parse(JSON.stringify(s));
      const resids = news?.filter((it) => it !== val);
      if(is_refresh === true){
        run({
          url: '/wbn-api/company_tag/update_company_tag',
          params: {
            company_id,
            tags: resids,
          },
          method:"PUT"
        });
      }
  

      return resids;
    });


  };

  return (
    <>
      <Modal
        {...modal}
        destroyOnClose={true}
        confirmLoading={loading}
        onOk={() => {
          run({
            url: '/wbn-api/company_tag/update_company_tag',
            params: {
              company_id,
              tags: saveTagids,
            },
            method:"PUT"
          });
        }}
      >
        <Spin spinning={myalltags?.loading}>
          <div>
            <span>已有标签</span>
            <div
              className="centerl"
              style={{ flexWrap: 'wrap', marginTop: 12, gap: 2, width: '100%' }}
            >
              {myalltags?.data
                ?.filter?.((it) => {
                  return saveTagids.includes(it?.id);
                })
                ?.map((it) => {
                  return (
                    <Tag
                      key={it?.id}
                      closable
                      onClose={(e) => {
                        e.preventDefault();
                        handleClose(it.id);
                      }}
                    >
                      {it?.name}
                    </Tag>
                  );
                })}

              <div className="center" style={{ width: '100%' }}>
                {saveTagids?.length === 0 && (
                  <span
                    style={{
                      width: '100%',
                      display: 'inline-block',
                      textAlign: 'center',
                      fontSize: 12,
                    }}
                  >
                    暂无数据
                  </span>
                )}
              </div>
            </div>
            <Divider />
            <div className="spread">
              <span style={{ flex: 1 }}>可选标签</span>
              <Input
                style={{ width: 160 }}
                placeholder="请输入关键词..."
                prefix={<SearchOutlined />}
                value={name}
                onChange={(e) => {
                  setName(e.target.value);
                }}
              />
            </div>
            <div className="centerl" style={{ flexWrap: 'wrap', marginTop: 12, gap: 2 }}>
              {myalltags?.data?.map((it) => (
                <Tag
                  key={it?.id}
                  style={{ cursor: 'pointer' }}
                  onClick={() => {
                    //adder
                    setSaveTagids((s) => {
                      const news = JSON.parse(JSON.stringify(s));
                      if (news.includes(it?.id)) {
                        //已存在
                      } else {
                        news.push(it?.id);
                      }
                      return news;
                    });
                  }}
                >
                  {it?.name}
                </Tag>
              ))}

              <AddTag
                tags={myalltags?.data?.map?.((it) => it?.name)}
                refresh={myalltags?.refresh}
              />
              {/* <Tag
              onClick={() => {
                setModal((s) => ({
                  ...s,
                  open: true,
                  title: '客户标签',
                }));
              }}
              style={tagPlusStyle}
            >
              <PlusOutlined /> 添加
            </Tag> */}
            </div>
          </div>
        </Spin>
      </Modal>

      <div className="centerl" style={{ flexWrap: 'wrap', marginTop: 12, gap: 2 }}>
        <span>客户标签:</span>
        {data?.map((it) => {
          return <Tag
            key={it?.id}
            closable
            onClose={(e) => {
              e.preventDefault();
              handleClose(it?.tag_id,true);
            }}
          >
            {it?.tag_name ?? "-"}
          </Tag>;
        })}
        <Tag
          onClick={() => {
            setModal((s) => ({
              ...s,
              open: true,
              title: '客户标签',
            }));
          }}
          style={tagPlusStyle}
        >
          <PlusOutlined /> 添加
        </Tag>
      </div>
    </>
  );
}

export default CUTags;
